'use strict';
const db = uniCloud.database();
const dbCmd = db.command;
const $ = dbCmd.aggregate;

exports.main = async (event, context) => {
  const flag = event.flag;
  if (flag === 'categories') { // 查询食谱的各个分类 
    return await db.collection("diet-categories").orderBy('sort', 'asc').get()
  } else if (flag === 0) { // 查询食谱各个分类的食谱
    const {
      category_id
    } = event;
    return await db.collection("diet").where({
      category_id
    }).orderBy('sort', 'asc').get()
  } else if (flag === 1) { // 查询每个食谱的详情
    const {
      _id
    } = event;
    return await db.collection("diet").aggregate()
      .match({
        _id,
      })
      .end();
  } else if (flag === 2) { //查询每个用户每个分类食谱的所规划的食物
    const {
      diet_id,
      id
    } = event;
    return await db.collection("diet-food").aggregate()
      .match({
        diet_id,
        id
      })
      .lookup({
        from: 'diet',
        let: {
          diet_id: '$diet_id',
        },
        pipeline: $.pipeline()
          .match(
            dbCmd.expr(
              $.eq(['$_id', '$$diet_id'])
            )
          )
          .project({
            _id: 0
          })
          .done(),
        as: 'dietList',
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$dietList', 0]), '$$ROOT'])
      })
      .project({
        dietList: 0
      })
      .end();
  } else if (flag === 3) { // 查询用户的食谱的所规划的食物
    const {
      diet_id,
      id
    } = event;
    return await db.collection("diet-food").aggregate()
      .match({
        diet_id,
        id
      })
      .end();
  } else if (flag === 4) { //新增菜谱食物
    const {
      foodList,
      id,
      diet_id,
    } = event
    return await db.collection("diet-food").add({
      foodList,
      id,
      diet_id,
    })
  } else if (flag === 5) { //更新菜谱食物
    const {
      foodList,
      id,
      diet_id,
    } = event
    return await db.collection("diet-food").where({
      id,
      diet_id,
    }).update({
      foodList,
    })
  }
};